package updater;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JOptionPane;

public class Update extends Thread {
	
	
	 public Update(String str) {
	        super(str);
	    }
	
	
	/**
	 * @param gui 
	 * @throws Exception 
	 */
	
         @Override
	public void run()   {
		
		Boolean isDone;
		
		File temp = new File(Path.loadFile()+"/temp");
	 	temp.mkdir();
		
		File resmods = new File(Path.loadFile()+"/res_mods");
		if (resmods.exists()) deleteDir(resmods);
		
		
		
		File path = new File(Path.loadFile());
		try {
			downloadFile("http://www.battlefieldclan.de/downloads/dgj_wot_mod_collection_v1.06.025.rar");
			File archive = new File(Path.loadFile()+"/temp/update.zip");
			
			try {
				ZipArchivExtractor.extractArchive(archive, path);
				isDone = true;
				File kill = new File(Path.loadFile()+"/temp");
				deleteDir(kill);
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "Fehler beim Entpacken!");
				File kill = new File(Path.loadFile()+"/temp");
				deleteDir(kill);
				isDone = false;
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Fehler beim Download!");
			File kill = new File(Path.loadFile()+"/temp");
			deleteDir(kill);
			isDone = false;
		}
		
		
		
		if (isDone == true){
		
			try {
				Popup.close();
				WotStart.wotStart();
				System.exit(0);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "XVM-Stats.Exe nicht gefunden!");
			}
		}
		
		
				
	}
	
	private static void deleteDir(File path) {
	      for (File file : path.listFiles()) {
	         if (file.isDirectory())
	            deleteDir(file);
	         file.delete();
	      }
	      path.delete();
	   }
	
         @SuppressWarnings("empty-statement")
	 private static void downloadFile( String http ) throws Exception {
	     
		 
		 	URL url = new URL( http );
	        URLConnection uc = url.openConnection();
	        InputStream in = uc.getInputStream();
             try (BufferedInputStream bis = new BufferedInputStream(
                     in)
             //int contentLength = getContentLength(uc);
             //if (contentLength == -1)
             //{
             //    System.err.println(
             //        "Could not obtain the content length. The ProgressMonitor " +
             //        "can not sensibly be displayed. Get over it.");
             //    return;
             //}
             ; FileOutputStream out = new FileOutputStream( Path.loadFile()+"/temp/update.zip" )) {
                 
                 byte[] buffer = new byte[1024];
                 for( int n; (n = bis.read(buffer)) != -1; out.write(buffer, 0, n) );
                 
                 out.flush();
             }
	  }

	 	
	}
	


